package articles_api

import (
	"context"
	"encoding/json"
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
)

// ArticleCollectsRemoveBatch 批量移除我收藏的文章
func (ArticlesApi) ArticleCollectsRemoveBatch(c *gin.Context) {
	var cr models.EsIDListRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}

	_claims, _ := c.Get("user")
	claims := _claims.(*utils.UserClaims)

	// 查询用户收藏文章 article_id
	var collects []models.UserCollectsModel
	var articleIDList []string

	err = common.DB.
		Find(&collects, "user_id = ? AND article_id = ?", claims.UserID, cr.IDList).
		Select("article_id").
		Scan(&articleIDList).Error
	if len(articleIDList) == 0 {
		http.FailWithMessage("请求非法", c)
		return
	}
	// 更新用户收藏
	// 同步 es
	// 传入id 列表, 查询es
	var idList []interface{}
	for _, s := range articleIDList {
		idList = append(idList, s)
	}
	boolSearch := elastic.NewTermsQuery("_id", idList...)
	result, err := common.EsClient.Search(models.ArticleModel{}.Index()).
		Query(boolSearch).
		Do(context.Background())

	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage(err.Error(), c)
		return
	}

	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err := json.Unmarshal(hit.Source, &article)
		if err != nil {
			common.Log.Error(err)
			http.FailWithMessage(err.Error(), c)
			return
		}
		err = ArticleModify(hit.Id, map[string]any{
			"collects_count": article.CollectsCount - 1,
		})
		if err != nil {
			common.Log.Error(err.Error())
			continue
		}
	}
	common.DB.Delete(&collects)
	http.IsOkWithMessage(fmt.Sprintf("成功取消收藏 %d 篇文章", len(articleIDList)), c)
}
